// server.js

const Koa = require('koa');
const Router = require('koa-router');
const next = require('next');
const bodyParser = require('koa-bodyparser');
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();
const PORT = 3001;
// 等到pages目录编译完成后启动服务响应请求
app.prepare().then(() => {
    const server = new Koa();
    const router = new Router();

    // start
    // 利用koa-router去把/a/1这种格式的路由
    // 代理到/a?id=1去，这样就不会404了
    router.get('/about/:id', async ctx => {
        const query = { id: ctx.params.id };
        const pathname = '/about';
        await handle(ctx.req, ctx.res, {
            pathname,
            query
        });
        ctx.respond = false;
    });
    router.get('/saga/:id/:page?', async ctx => {
        const query = { id: ctx.params.id, page: ctx.params.page };
        const pathname = '/saga';
        await handle(ctx.req, ctx.res, {
            pathname,
            query
        });
        ctx.respond = false;
    });
    router.get('/thunk/:id/:page?', async ctx => {
        const query = { id: ctx.params.id, page: ctx.params.page };
        const pathname = '/thunk';
        await handle(ctx.req, ctx.res, {
            pathname,
            query
        });
        ctx.respond = false;
    });
    router.get('/detail/:id/', async ctx => {
        const query = { id: ctx.params.id };
        const pathname = '/detail';
        await handle(ctx.req, ctx.res, {
            pathname,
            query
        });
        ctx.respond = false;
    });
    // server.use(bodyParser());
    router.all('*', async ctx => {
        await handle(ctx.req, ctx.res);
        ctx.respond = false;
    });
    server.use(async (ctx, next) => {
        ctx.res.statusCode = 200;
        await next();
    });

    server.use(router.routes());
    server.listen(3001, () => {
        console.log(`> Ready on http://localhost:3001`);
    });
});
